package test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import tool.DBUtil;

public class PolicyService extends JFrame {
    private Connection conn; // 数据库连接
    private List<JPanel> policyPanels; // 提升为类成员变量

    public PolicyService() {
        this.setTitle("政策信息");
        this.setSize(600, 400);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(null);

        try {
            conn = DBUtil.getConnection();
            if (conn == null) {
                JOptionPane.showMessageDialog(this, "数据库连接为空，请检查配置", "警告", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "数据库连接失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            conn = null;
        }

        JTabbedPane tabbedPane = new JTabbedPane();
        this.policyPanels = new ArrayList<>(); // 初始化成员变量

        try {
            if (conn != null) {
                this.policyPanels = createPolicyPanels(); // 成员变量赋值
            } else {
                JOptionPane.showMessageDialog(this, "无法加载政策面板，请检查数据库连接", "警告", JOptionPane.WARNING_MESSAGE);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "加载政策面板失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            this.policyPanels.clear(); // 可选：确保列表为空
        }

        for (int i = 0; i < this.policyPanels.size(); ++i) {
            tabbedPane.addTab("政策 " + (i + 1), this.policyPanels.get(i));
        }

        // 新增按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增政策");
        JButton editButton = new JButton("修改政策");
        JButton deleteButton = new JButton("删除政策");

        addButton.addActionListener(e -> addPolicy());
        editButton.addActionListener(e -> editPolicy(this.policyPanels)); // 引用成员变量
        deleteButton.addActionListener(e -> deletePolicy(this.policyPanels)); // 引用成员变量

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);

        this.add(tabbedPane, BorderLayout.CENTER);
        this.add(buttonPanel, BorderLayout.SOUTH);

        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                MannageService.main((String[]) null);
                PolicyService.this.dispose();
            }
        });

        this.setVisible(true);
    }

    List<JPanel> createPolicyPanels() throws SQLException {
        List<JPanel> panels = new ArrayList<>();
        String sql = "SELECT policyID, title, content, image_url FROM policymessage"; // 修改字段为 policyID
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {
            int policyID = rs.getInt("policyID"); // 使用 policyID 替代 id
            JPanel panel = new JPanel(new BorderLayout());

            JLabel titleLabel = new JLabel(rs.getString("title"));
            titleLabel.setFont(new Font("SimSun", Font.BOLD, 18));
            panel.add(titleLabel, BorderLayout.NORTH);

            JTextArea descriptionArea = new JTextArea(rs.getString("content"));
            descriptionArea.setEditable(false);
            descriptionArea.setLineWrap(true);
            descriptionArea.setWrapStyleWord(true);
            panel.add(new JScrollPane(descriptionArea), BorderLayout.CENTER);

            JLabel linkLabel = new JLabel(rs.getString("image_url"));
            linkLabel.setFont(new Font("SimSun", Font.PLAIN, 14));
            panel.add(linkLabel, BorderLayout.SOUTH);

            // 将 policyID 存入 ClientProperty 供后续操作使用
            panel.putClientProperty("policyID", policyID); // 修改 key 名为 policyID

            panels.add(panel);
        }

        rs.close();
        pstmt.close();

        return panels;
    }

    private void addPolicy() {
        String title = JOptionPane.showInputDialog(this, "请输入政策标题:");
        if (title == null || title.trim().isEmpty()) return;

        String content = JOptionPane.showInputDialog(this, "请输入政策内容:");
        if (content == null || content.trim().isEmpty()) return;

        String imageUrl = JOptionPane.showInputDialog(this, "请输入图片链接:");

        try {
            String sql = "INSERT INTO policymessage (title, content, image_url) VALUES (?, ?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, title);
            pstmt.setString(2, content);
            pstmt.setString(3, imageUrl);
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "政策已成功添加");
            refreshPolicies();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "添加政策失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void editPolicy(List<JPanel> panels) {
        int index = JOptionPane.showOptionDialog(this, "请选择要修改的政策:", "修改政策",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                panels.toArray(), null);

        if (index < 0) return;

        JPanel selectedPanel = panels.get(index);
        int policyID = (Integer) selectedPanel.getClientProperty("policyID"); // 获取 policyID

        try {
            String sql = "SELECT title, content, image_url FROM policymessage WHERE policyID = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, policyID);
            ResultSet rs = pstmt.executeQuery();

            if (!rs.next()) {
                JOptionPane.showMessageDialog(this, "未找到该政策", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            String title = JOptionPane.showInputDialog(this, "修改标题:", rs.getString("title"));
            String content = JOptionPane.showInputDialog(this, "修改内容:", rs.getString("content"));
            String imageUrl = JOptionPane.showInputDialog(this, "修改图片链接:", rs.getString("image_url"));

            String updateSql = "UPDATE policymessage SET title = ?, content = ?, image_url = ? WHERE policyID = ?";
            PreparedStatement updateStmt = conn.prepareStatement(updateSql);
            updateStmt.setString(1, title);
            updateStmt.setString(2, content);
            updateStmt.setString(3, imageUrl);
            updateStmt.setInt(4, policyID);
            updateStmt.executeUpdate();

            JOptionPane.showMessageDialog(this, "政策更新成功");
            refreshPolicies();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "更新政策失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void deletePolicy(List<JPanel> panels) {
        int index = JOptionPane.showOptionDialog(this, "请选择要删除的政策:", "删除政策",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                panels.toArray(), null);

        if (index < 0) return;

        JPanel selectedPanel = panels.get(index);
        int policyID = (Integer) selectedPanel.getClientProperty("policyID"); // 获取 policyID

        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除这条政策吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm != JOptionPane.YES_OPTION) return;

        try {
            String sql = "DELETE FROM policymessage WHERE policyID = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, policyID);
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "政策删除成功");
            refreshPolicies();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "删除政策失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void refreshPolicies() {
        JTabbedPane tabbedPane = (JTabbedPane) this.getComponent(0);
        tabbedPane.removeAll();

        try {
            this.policyPanels = createPolicyPanels(); // 更新成员变量
            for (int i = 0; i < this.policyPanels.size(); ++i) {
                tabbedPane.addTab("政策 " + (i + 1), this.policyPanels.get(i));
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "刷新政策失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PolicyService());
    }
}
